package com.hrm.document.handler;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hrm.commons.beans.Document;
import com.hrm.commons.beans.User;
import com.hrm.document.service.IDocumentService;
import com.hrm.utils.PageModel;

@Controller
@RequestMapping("/document")
public class DocumentHandler {

	@Autowired
	private IDocumentService documentService;
	
	@RequestMapping("/findDocument.do")
	public String findDocument(@RequestParam(defaultValue="1")Integer pageIndex, String title, Model model) {
		PageModel pageModel = new PageModel();
		pageModel.setPageIndex(pageIndex);
		
		int count = documentService.findDocumentCount(title);
		
		pageModel.setRecordCount(count);
		
		List<Document> documents = documentService.findDocument(title, pageModel);
		
		model.addAttribute("title", title);
		model.addAttribute("documents", documents);
		model.addAttribute("pageModel", pageModel);
		return "/jsp/document/document.jsp";
	}
	
	@RequestMapping("/addDocument.do")
	public String addDocument(Document document, Model model, HttpSession session) throws IllegalStateException, IOException {
		//System.out.println(document);
		//文件上传的路径
		String path = "E:/upload";//session.getServletContext().getRealPath("/upload");
		//System.out.println(path);
		File upload = new File(path);
		if(!upload.exists()) {
			upload.mkdirs();
		}
		//上传后保存的文件的名称
		String filename = document.getFile().getOriginalFilename();
		//将上传的文件保存到指定路径指定的文件名
		document.getFile().transferTo(new File(path+File.separator+filename));
		
		document.setFilename(filename);
		
		User user = (User) session.getAttribute("login_user");
		document.setUser(user);
		
		int rows = documentService.addDocument(document);
		if(rows > 0) {
			return "redirect:/document/findDocument.do";
		}else {
			model.addAttribute("fail", "文档上传失败！");
			return "/jsp/fail.jsp";
		}
	}
	
	@RequestMapping("/modifyDocument.do")
	public String modifyDocument(String flag, Document document, Model model, HttpSession session) throws IllegalStateException, IOException {
		if(flag.equals("1")) {
			Document target = documentService.findDocumentById(document.getId());
			model.addAttribute("document", target);
			return "/jsp/document/showUpdateDocument.jsp";
		}else {
			if(!document.getFile().isEmpty()) {
				//如果修改页面重新上传的文件不为空
				String path = "E:/upload";
				Document target = documentService.findDocumentById(document.getId());
				File targetFile = new File(path, target.getFilename());
				if(targetFile.exists()) {
					//删除原来的文件
					targetFile.delete();
				}
				String fileName = document.getFile().getOriginalFilename();
				document.getFile().transferTo(new File(path+File.separator+fileName));
				document.setFilename(fileName);
			}
			User user = (User) session.getAttribute("login_user");
			document.setUser(user);
			
			int rows = documentService.modifyDocument(document);
			if(rows > 0) {
				return "redirect:/document/findDocument.do";
			}else {
				model.addAttribute("fail", "文档修改失败！");
				return "/jsp/fail.jsp";
			}
		}
	}
	
	@RequestMapping("/removeDocument.do")
	public String removeDocument(Integer[] ids, Model model){
		int rows = 0;
		for(Integer id:ids){
			String path = "E:/upload";
			Document target = documentService.findDocumentById(id);
			String fileName = target.getFilename();
			//从本地磁盘删除文件
			File targetFile = new File(path, fileName);
			if(targetFile.exists()){
				targetFile.delete();
			}
			//从数据库表中删除对应数据
			int i = documentService.removeDocument(id);
			rows = rows + i;
		}
		if(rows == ids.length){
			return "redirect:/document/findDocument.do";
		}else{
			model.addAttribute("fail", "文档删除失败！");
			return "/jsp/fail.jsp";
		}
	}
	
	@RequestMapping("/downLoad.do")
	public ResponseEntity<byte[]> download(Integer id, HttpServletRequest request) throws IOException{
		String path = "E:/upload";
		Document target = documentService.findDocumentById(id);
		String fileName = target.getFilename();
		
		File file = new File(path+File.separator+fileName);
		//解决除IE外浏览器中文乱码问题
		//String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso8859-1");
		String downloadFileName = processFileName(request, fileName);
		
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", downloadFileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);//.OK
	}
	
	//解决IE、谷歌、火狐浏览器乱码问题
	public String processFileName(HttpServletRequest request, String fileNames){
		String codedfilename = null;
		try{
			String agent = request.getHeader("USER-AGENT");
			if(null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")){
				//IE
				String name = java.net.URLEncoder.encode(fileNames, "UTF-8");
				codedfilename = name;
			}else if(null != agent && -1 != agent.indexOf("Mozilla")){
				//火狐、谷歌等
				codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return codedfilename;
	}
}